#!/usr/bin/perl
use strict;
open(FH, "/proc/cpuinfo") || die $!;

my $line;
my ($cpu, $core, $phy);
my ($cpuid, $coreid, $phyid);
my %cpuinfo;
my $confdir = "/opt/fusionstack/lich/cgroup";
my $cg_global_conf="/opt/fusionstack/etc/cgroup.conf";

if(-f "$confdir/kvm.conf"){
	unlink  "$confdir/kvm.conf";
}
if( -f "$confdir/lich.conf"){
	unlink "$confdir/lich.conf";
}
if( -f "$confdir/hosts"){
	unlink  "$confdir/hosts";
}
if(-f "$confdir/hazpid"){
	unlink  "$confdir/hazpid";
}
open(CG, $cg_global_conf)||die $!;
my $conf=<CG>;
my $res = eval $conf;
my $total_mem = `cat /proc/meminfo  |awk '{if(\$1=="MemTotal:"){print \$2}}'`;
chomp $total_mem;

if($total_mem < (4 * 1024 * 1024 )){
	exit 2;
}
$total_mem *= 1024;
my $lich_mem = $total_mem * $res->{lichmem} / ($res->{lichmem} + $res->{kvmmem});
$lich_mem=~s/\..*//;

if($lich_mem > 8 * 1024 * 1024 * 1024){
	$lich_mem = 8 * 1024 * 1024 * 1024;	
} elsif($lich_mem < 4 * 1024 * 1024 * 1024) {
	$lich_mem = 4 * 1024 * 1024 * 1024
}

my $kvm_mem = $total_mem  - $lich_mem ;
print "total mem $total_mem kvm mem $kvm_mem lich mem $lich_mem \n";
while($line=<FH>)
{
	chomp $line;
	if($line=~/^processor/){
		$cpu++;
		
		($cpuid=$line)=~s/processor	: //;
#		print "the line is $cpu, $cpuid \n";
		next;	
	}

	if($line=~/^physical id/){
		$phy++;

		($phyid=$line)=~s/physical id	: //;
#		print "the physical id is $phyid count $phy\n";
		next;
	}

	if($line=~/^core id/){
		$core++;

		($coreid=$line)=~s/core id		: //;
#		print "the core id is $coreid count $core\n";
	}
	else {
		next;
	}

#	print "============================\n";
	
#	print "push $cpuid to $phyid $coreid\n";
	
	push @{$cpuinfo{$phyid}->{$coreid}}, $cpuid;
}

close FH;
my $lichreqnum=$cpu * ($res->{lichcpu}/($res->{kvmcpu} + $res->{lichcpu}));
my $kvmreqnum=$cpu * ($res->{kvmcpu}/($res->{kvmcpu} + $res->{lichcpu}));
#if($kvmreqnum >= $cpu){
#	print "req cpu number more than $cpu\n";
#	exit 2;
#}
#if($reqnum <= 0){
#	print "req cpu number is less than 1\n";
#	exit 1;
#}

if($cpu % ($res->{kvmcpu} + $res->{lichcpu}) != 0){
	print "kvm cpu $res->{kvmcpu} and lich $res->{lichcpu} cpu number  set  is incorrect\n";
	exit 1;
}
my $ret;
my $ret1;
my $req = 0;
for my $k (keys %cpuinfo)
{
	for my $k1 (keys %{$cpuinfo{$k}})
	{
		for my $cid(sort @{$cpuinfo{$k}->{$k1}})
		{
			if($kvmreqnum > 0){
				$kvmreqnum--;
				$ret.="$cid,";
			}
			else{
				if($req < $lichreqnum){
					$ret1.="$cid,";
					$req++;
				}
			}
		}	 
	}
}

$ret=~s/,$//;
$ret1=~s/,$//;


print "kvm mem $kvm_mem\n";

open(KVM, ">$confdir/kvm.conf") ||die $!;
print KVM "RUNTIME_US=0\n";
print KVM "PERIOD_US=1000000\n";
print KVM "SWAP=50\n";
print KVM "CPUSET=$ret\n";
print KVM "MEMLIMIT=$kvm_mem\n";
close KVM;

open(LICH, ">$confdir/lich.conf")||die $!;
print LICH "RUNTIME_US=0\n";
print LICH "PERIOD_US=1000000\n";
print LICH "SWAP=0\n";
print LICH "CPUSET=$ret1\n";
print LICH "MEMLIMIT=200G\n";
close LICH;
